package paythere

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/pay/base"
)

type Factory struct {
}

func (p *Factory) CreatePay(config base.Config) base.Payment {
	return &Paythree{
		Url:        config.Url,
		MerchantId: config.MerchantId,
		SecretKey:  config.SecretKey,
		ReturnUrl:  config.ReturnUrl,
		NotifyUrl:  config.NotifyUrl,
	}
}

type Paythree struct {
	Url        string `json:"url"`         // 网关//
	MerchantId string `json:"merchant_id"` // 商户账号
	SecretKey  string `json:"secret_key"`  // 代收秘钥
	ReturnUrl  string `json:"return_url"`
	NotifyUrl  string `json:"notify_url"`
}

//	type Params struct {
//		MerchantRef string `json:"merchant_ref"`
//		Product     string `json:"product"`
//		Amount      string `json:"amount"`
//		Extra       extra  `json:"extra"`
//	}
//
//	type extra struct {
//		FiatCurrency string `json:"fiat_currency"`
//	}
type Resp struct {
	Status  string `json:"status"`
	Message string `json:"message"`
	Data    data   `json:"data"`
}

type data struct {
	OrderStatus     string `json:"orderStatus"`
	OrderMessage    string `json:"orderMessage"`
	MerchantOrderNo string `json:"merchantOrderNo"`
	PlatOrderNo     string `json:"platOrderNo"`
	PaymentInfo     string `json:"paymentInfo"`
	PayAmount       string `json:"payAmount"`
	Description     string `json:"description"`
	Sign            string `json:"sign"`
}

const MXN01 = "MXN01" // 代收方式 ，墨西哥：MXN01

// 代收订单创建
func (p *Paythree) Pay(ctx context.Context, req map[string]any) (resp base.PayResponse, err error) {
	orderNo := req["orderNo"].(string)
	amount := fmt.Sprintf("%.2f", req["amount"])
	// 请求参数
	params := map[string]any{
		"merchantNo":      p.MerchantId,
		"method":          MXN01,
		"merchantOrderNo": orderNo,
		"payAmount":       amount,
		"mobile":          "8749464654",
		"name":            "test-name",
		"email":           "test@test.com",
		"notifyUrl":       p.NotifyUrl,
		"returnUrl":       p.ReturnUrl,
		"description":     "recharge test",
	}
	// 生成签名
	sign, err := GenerateSignature(params, p.SecretKey)
	params["sign"] = sign

	// 发送请求
	str, err := base.SendPostJson(context.Background(), p.Url, params)
	if err != nil {
		return resp, err
	}
	var respData Resp
	err = json.Unmarshal([]byte(str), &respData)
	if err != nil {
		return resp, err
	}
	if respData.Status != "200" && respData.Message != "success" {
		return resp, errors.New(respData.Message)
	}
	resp = base.PayResponse{
		Url:     respData.Data.PaymentInfo,
		OrderNo: respData.Data.PlatOrderNo,
	}
	return resp, nil

}
